<template>
  <div style="background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:26px; font-weight: bold">订单金额报表</span>
  </div>
  <el-card style="margin: 20px;">
    <el-form style="padding-top:10px;">
      <el-row :gutter="30">
        <el-col :span="6">
          <el-form-item label="分店选择" style="width:250px;">
            <el-select placeholder="请选择所属分店" v-model="searchForm.branchId" :display-method="displayData" @change="loadStatement">
              <el-option v-for="item in branchOptions"
                         :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="年份选择" style="width:250px;">
            <el-select v-model="searchForm.year" placeholder="请选择年份">
              <el-option v-for="item in [2023,2024]" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="loadStatement">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <div class="report-page">
    <el-card>
      <div ref="chart" style="width: 100%; height: 400px;"></div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick, watch} from 'vue'
import * as echarts from 'echarts'
import {ElCard, ElMessage} from 'element-plus'
import qs from "qs";
import axios from "axios";

// 定义查询表单
const searchForm = ref({
  branchId: 0,
  branchName: '',
  year: 2024
})
// 定义从后端查询到的报表数据
const statementData = ref([]);

function displayData() {
  return searchForm.value.branchName;
}
// 定义加载订单报表数据
const loadStatement = () => {

  // 清空数据，再次查询其他时间或者分店
  orderData.values = new Array(12).fill(0);
  // 加载订单报表数据
  let data = qs.stringify(searchForm.value);
  axios.get(BASE_URL+'/v1/statement/select?'+data).then(response=>{
    if(response.data.code===2000){
      console.log(response.data.data);
      statementData.value = response.data.data;
      console.log(statementData.value.length)
     /* statementData.value.forEach(item => {
        const monthIndex = item.month.split('-')[1] - 1; // 获取月份索引（0-11）
        orderData.values[monthIndex] = item.totalAmount;

      });*/
      if (statementData.value.length > 0) {
        statementData.value.forEach(item => {
          const monthIndex = item.month.split('-')[1] - 1; // 获取月份索引（0-11）
          orderData.values[monthIndex] = item.totalAmount;
        });
      }else {
        // 如果没有数据，清空图表
        orderData.values = new Array(12).fill(0);
      }
      // 初始化图表
      initChart();
      console.log(orderData);
    }else {
      ElMessage.error(response.data.msg);
      // 如果没有数据，清空图表
      orderData.values = new Array(12).fill(0);
      initChart();
    }
})

}


// 定义保存餐厅数据的数组
const branchOptions = ref([]);
// 通过id显示餐厅的对应显示名称
const formatRoleTable = (row,column,cellValue,index)=>{
  if(!branchOptions.value){
    return cellValue;
  }
  for(let item of branchOptions.value){
    if(item.id==cellValue){
      cellValue = item.name;
    }
  }
  return cellValue;
};
// 加载所有分店数据
onMounted(
    () => {
      getBranchByStatus(branchOptions);

      loadStatement();
    }
)
// 监听 branchOptions 的变化
watch(branchOptions, (newVal) => {
  nextTick(() => {
    if (newVal.length > 0) {
      searchForm.value.branchId = newVal[0].id
      console.log("test" + searchForm.value.branchId)
      loadStatement();
    } else {
      ElMessage.error("数据出错了");
      searchForm.value.branchId = 101
    }
  })
})


// 模拟订单数据
const orderData = {
  categories: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  values:  new Array(12).fill(0) // 初始化为0
}

const chart = ref(null)

const initChart =() => {
  // 初始化 ECharts 实例
  const myChart = echarts.init(chart.value)

  // 配置项
  const option = {
    title: {
      text: '每月订单总金额统计'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = '';
        params.forEach(param => {
          result += `${param.seriesName}<br/>${param.name}: ${param.value} 元`;
        });
        return result;
      }
    },
    xAxis: {
      type: 'category',
      data: orderData.categories
    },
    yAxis: {
      type: 'value',
      name: '总金额（元）'
    },
    series: [
      {
        name: '总金额',
        type: 'bar',
        data: orderData.values
      }
    ]
  };

  // 使用配置项设置图表
  myChart.setOption(option)
};
</script>

<style scoped>
.report-page {
  padding: 20px;
}
</style>